package com.entrogy.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.entrogy.bean.*;
import com.entrogy.service.SalarySlipService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** 解析监听器，
 * 每解析一行会回调invoke()方法。
 * 整个excel解析结束会执行doAfterAllAnalysed()方法
 **/
public class TeacherSalaryExcelListener extends AnalysisEventListener<Map<Integer, String>> {

    private Logger logger = LoggerFactory.getLogger(TeacherSalaryExcelListener.class);

    private SalarySlipService salarySlipService;

    // 操作人id
    private String createUserId;

    // 导入工资条的月份
    private Integer salaryMonth;

    // 导入工资条的月份
    private Integer salaryYear;

    // 工资条模板id
    private Integer templateId;

    // 学校id
    private Integer schoolCode;

    // 导入数据的工资组成id
    private List<Integer> salaryComposeIdList = new ArrayList<>();

    // 解析出来的数据
    private List<SalaryTeacherDetailEntity> salaryTeacherDetailList = new ArrayList<>();

    public TeacherSalaryExcelListener() {
    }

    public TeacherSalaryExcelListener(Integer salaryYear, Integer salaryMonth, Integer templateId, String createUserId, Integer schoolCode, SalarySlipService salarySlipService) {
        this.salaryMonth = salaryMonth;
        this.salaryYear = salaryYear;
        this.templateId = templateId;
        this.createUserId = createUserId;
        this.salarySlipService = salarySlipService;
        this.schoolCode = schoolCode;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        String firstCell = headMap.get(0);
        if ("工资条构成ID".equals(firstCell)){
            // excel第一行第一个单元格为无用数据，之后为工资组成id
            headMap.forEach((k, v) -> {
                if (k > 1){
                    salaryComposeIdList.add(Integer.valueOf(v));
                }
            });
        }
    }

    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        // 第一行为教师id
        String teacherId = data.get(0);
        if (!StringUtils.isNoneBlank(teacherId)){
            return;
        }
        // 第三行开始，就是员工的薪水
        List<BigDecimal> salary = new ArrayList<>();
        data.forEach((k, v) -> {
            if (k > 1)
                salary.add(v == null ? null : new BigDecimal(v));
        });
        // 根据导入日期去查询这个教师的工资条id,没有这个工资条id，那么就是第一次导入，所以工资条信息为空（撤回状态为未撤回，教师如果有工资条数据的话，他的未撤回的工资条数据只会有一条）
        List<SalaryTeacherInfoEntity> salaryTeacherInfoList = salarySlipService.ListTeacherSalarySlipId(salaryYear, salaryMonth, teacherId, null, null, null, null);
        Integer salaryTeacherInformationId = null;
        if (salaryTeacherInfoList.size() != 0){
            // 这行数据对应的工资条id
            salaryTeacherInformationId = salaryTeacherInfoList.get(0).getId();
        }
        if (salary.size() != salaryComposeIdList.size()){
            logger.error("导入工资条时失败，工资内容和表头信息不匹配！");
            throw new RuntimeException();
        }
        for (int i = 0; i < salary.size(); i++) {
            SalaryTeacherDetailEntity salaryTeacherDetail = new SalaryTeacherDetailEntity();
            BigDecimal salaryValue = salary.get(i) == null ? new BigDecimal(0) : salary.get(i);
            Integer salaryComposeId = Integer.valueOf(salaryComposeIdList.get(i));
            salaryTeacherDetail.setSalaryComposeId(salaryComposeId)
                    .setTeacherId(teacherId)
                    .setValue(salaryValue.doubleValue())
                    .setSalaryTeacherInformationId(salaryTeacherInformationId);
            if (i == 0){
                // 入库前需要将该教师该月的工资条详细数据删除（工资条id不为null才删除）
                if (salaryTeacherDetail.getSalaryTeacherInformationId() != null){
                    boolean deleteTeacherSalaryInfo = salarySlipService.deleteTeacherSalaryInfo(salaryTeacherDetail.getSalaryTeacherInformationId());
                    boolean deleteResult = salarySlipService.deleteTeacherSalaryDetail(salaryTeacherDetail.getSalaryTeacherInformationId());
                }
                // 首先插入教师的工资条信息(只插入一次)
                SalaryTeacherInfoEntity salaryTeacherInfoEntity = new SalaryTeacherInfoEntity();
                salaryTeacherInfoEntity.setTeacherId(salaryTeacherDetail.getTeacherId()).setSalaryMonth(salaryMonth).setSalaryYear(salaryYear).setCreateUserId(createUserId);
                boolean insertTeacherSalaryInfo = salarySlipService.insertSalaryInformation(salaryTeacherInfoEntity);
                salaryTeacherInformationId = salaryTeacherInfoEntity.getId();
                salaryTeacherDetail.setSalaryTeacherInformationId(salaryTeacherInformationId);
            }
            salaryTeacherDetailList.add(salaryTeacherDetail);
        }
    }

    //整个excel解析结束会执行doAfterAllAnalysed()方法
    public void doAfterAllAnalysed(AnalysisContext context) {
        logger.info("正在进行工资条导入，导入的数据为=>" + salaryTeacherDetailList);
        boolean result = salarySlipService.insertBatchSalary(salaryTeacherDetailList);
        salaryTeacherDetailList.clear();
    }
}

